#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::fs;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

fn main() {
    core_api::run();
    tauri::Builder::default()
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_dialog::init())
        .invoke_handler(tauri::generate_handler![greet, validate_file])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

#[derive(Serialize, Deserialize, Debug)]
struct ValidateResult {
    pub name: String,
    pub result: bool,
}

#[tauri::command]
fn validate_file(path: &str, is_file: bool) -> Vec<ValidateResult> {
    println!("{},{}", path, is_file);
    // let p = PathBuf::from(path);
    if is_file {
        vec![ValidateResult {
            name: path.to_string(),
            result: core_api::checksum::validate_checksum(path).is_ok(),
        }]
    } else {
        let files = list_mp4_files(path);
        files
            .iter()
            .map(|p| ValidateResult {
                name: p.to_string_lossy().to_string(),
                result: core_api::checksum::validate_checksum(p.to_str().unwrap()).is_ok(),
            })
            .collect()
    }
}

fn list_mp4_files(path: &str) -> Vec<PathBuf> {
    let list = fs::read_dir(path)
        .unwrap()
        .filter_map(|entry_r| entry_r.ok())
        .filter(|entry| entry.file_type().unwrap().is_file())
        .filter(|entry| {
            entry
                .path()
                .extension()
                .and_then(std::ffi::OsStr::to_str)
                .map_or(false, |ext| ext == "mp4")
        })
        .map(|entry| entry.path())
        .collect();

    list
}
